package cn.nfwx.tv.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import cn.nfwx.tv.R;
import cn.nfwx.tv.callback.ResponseCallback;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.events.ToMineItemEvent;
import cn.nfwx.tv.fragment.dialog.SmsCheckDialogFragment;
import cn.nfwx.tv.fragment.dialog.WebViewDialogFragment;
import cn.nfwx.tv.fragment.me.MineFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.EditNullFilter;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.manager.UserManager;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.User;
import cn.nfwx.tv.okhttp.UrlHelper;
import cn.nfwx.tv.util.AppUtil;
import cn.nfwx.tv.util.SpannableStringUtils;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.util.ToolUtil;

public class LoginSmsView extends LinearLayout implements View.OnClickListener, Handler.Callback {

    private static final int SMSTIME = 60;
    private static final int MSG_COUNT_LOGIN = 1;//短信登录
    private static final int MSG_SUCCESS = 2;
    private static final int MSG_FAILURE = 3;
    private static final int LOGIN_SUCCESS = 4;
    private static final int LOGIN_FAILURE = 5;
    private final FragmentManager mFragmentManager;

    private TextView btn_login_sms_code;
    private ItemEditView iev_sms_phone, iev_sms_text;
    private CheckBox cb_sms;

    private int countDown = SMSTIME;
    private Handler mhandler = new Handler(this);

    public LoginSmsView(Context context) {
        this(context, null);
    }

    public LoginSmsView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoginSmsView(final Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater.from(context).inflate(R.layout.layout_login_sms, this, true);
        AppCompatActivity activity = AppUtil.getAppCompActivity(context);
        mFragmentManager = activity.getSupportFragmentManager();

        btn_login_sms_code = findViewById(R.id.btn_login_sms_code);
        iev_sms_phone = findViewById(R.id.iev_sms_phone);
        iev_sms_text = findViewById(R.id.iev_sms_text);
        cb_sms = findViewById(R.id.cb_sms);
        iev_sms_phone.setFilters(new InputFilter[]{new EditNullFilter(), new InputFilter.LengthFilter(11)});
        iev_sms_text.setFilters(new InputFilter[]{new EditNullFilter(), new InputFilter.LengthFilter(6)});
        /**
         * 设置富文本
         */
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                WebViewDialogFragment dialogFragment = WebViewDialogFragment.newInstance(UrlHelper.getAppAgreement());
                DialogFragmentHelper.showDialogFragment(mFragmentManager, dialogFragment);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                if (context == null) {
                    return;
                }
                ds.setColor(context.getResources().getColor(R.color.setting_content_text));
                ds.setUnderlineText(true);
                ds.clearShadowLayer();
            }
        };
        TextView agreement_btn = findViewById(R.id.agreement_btn);
        SpannableStringBuilder stringBuilder = SpannableStringUtils.getBuilder("")
                .append(context.getString(R.string.register_notice))
                .setForegroundColor(context.getResources().getColor(R.color.setting_lab_text))
                .append(context.getString(R.string.app_agreentment))
                .setClickSpan(clickableSpan)
                .setFlag(Spanned.SPAN_INCLUSIVE_INCLUSIVE).create();
        agreement_btn.setText(stringBuilder);
        agreement_btn.setMovementMethod(LinkMovementMethod.getInstance());

        initLinten();
    }

    /**
     * 自动登录
     */
    public void autoLogin() {
        iev_sms_phone.setText("18910158363");
        iev_sms_text.setText("000000");
        onClick(findViewById(R.id.login_btn));
    }

    private void initLinten() {
        btn_login_sms_code.setOnClickListener(this);
        findViewById(R.id.login_btn).setOnClickListener(this);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_COUNT_LOGIN:
                if (countDown >= 0) {
                    btn_login_sms_code.setText(countDown-- + "s");
                    mhandler.sendEmptyMessageDelayed(MSG_COUNT_LOGIN, 1000);
                } else {
                    btn_login_sms_code.setClickable(true);
                    countDown = SMSTIME;//复位，60s倒计时完后可以继续倒计时
                    btn_login_sms_code.setText("获取验证码");
                    mhandler.removeMessages(MSG_COUNT_LOGIN);
                }
                break;
            case MSG_SUCCESS:
                btn_login_sms_code.setClickable(false);
                DialogFragmentHelper.closeLoadingDialog(mFragmentManager);
                mhandler.sendEmptyMessage(MSG_COUNT_LOGIN);
                Toast.makeText(getContext(), "短信已发送", Toast.LENGTH_LONG).show();
                break;
            case MSG_FAILURE:
                String message = (String) msg.obj;
                DialogFragmentHelper.closeLoadingDialog(mFragmentManager);
                btn_login_sms_code.setClickable(true);
                btn_login_sms_code.setText("获取验证码");
                if (TextUtils.isEmpty(message)) {
                    message = "短信发送失败,请稍后再尝试";
                }
                ToastUtil.show(getContext(), message);
                break;
            case LOGIN_SUCCESS:
                JSONObject response = (JSONObject) msg.obj;
                DialogFragmentHelper.closeLoadingDialog(mFragmentManager);
                Result<User> result = JSON.parseObject(response.toString(), new TypeReference<Result<User>>() {
                }.getType());
                if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                    if (result.getData() != null && result.getData().getUid() != 0) {
                        AccountHelper.getInstance().saveUser(getContext(), result.getData());
                        ToastUtil.show(getContext(), "登录成功", Toast.LENGTH_LONG);
                        EventBus.getDefault().post(new ToMineItemEvent(MineFragment.POSITION_SUBSCRIPT));
                        mhandler.removeCallbacksAndMessages(null);
                    }
                } else {
                    ToastUtil.show(getContext(), result.getMessage());
                }
                break;
            case LOGIN_FAILURE:
                DialogFragmentHelper.closeLoadingDialog(mFragmentManager);
                ToastUtil.show(getContext(), "登录失败");
                break;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login_sms_code:
                String smsMobileNo = iev_sms_phone.getText().toString();
                if (TextUtils.isEmpty(smsMobileNo)) {
                    Toast.makeText(getContext(), getContext().getResources().getString(R.string.toast_phone), Toast.LENGTH_LONG).show();
                    return;
                }
                if (!ToolUtil.isPhoneLegal(smsMobileNo)) {
                    Toast.makeText(getContext(), getContext().getResources().getString(R.string.toast_right_phone), Toast.LENGTH_LONG).show();
                    return;
                }

                AppCompatActivity activity = AppUtil.getAppCompActivity(getContext());
                if (activity != null) {
                    SmsCheckDialogFragment fragment = SmsCheckDialogFragment.newInstance(smsMobileNo);
                    fragment.setValueCallback(new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                            countDown = 60;
                            btn_login_sms_code.setClickable(false);
                            mhandler.removeMessages(MSG_SUCCESS);
                            mhandler.sendEmptyMessage(MSG_SUCCESS);
                        }
                    });
                    DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), fragment);
                }

//                countDown = 60;
//                btn_login_sms_code.setClickable(false);
//
//                DialogFragmentHelper.showLoadingDialog(mFragmentManager);
//                UserManager.requestIjkSmsCode(getContext(), smsMobileNo, new ResponseCallback<Integer>() {
//                    @Override
//                    public void onSuccess(String requestTag, final Integer response) {
//                        if (response > 0) {
//                            mhandler.removeMessages(MSG_SUCCESS);
//                            mhandler.sendEmptyMessage(MSG_SUCCESS);
//                        } else {
//                            mhandler.removeMessages(MSG_FAILURE);
//                            mhandler.sendEmptyMessage(MSG_FAILURE);
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(String requestTag, String message) {
//                        mhandler.removeMessages(MSG_FAILURE);
//                        Message msg = mhandler.obtainMessage(MSG_FAILURE, message);
//                        mhandler.sendMessage(msg);
//                    }
//                });
                break;
            case R.id.login_btn:
                final String smsLoginPhone = iev_sms_phone.getText().toString().trim();
                if (TextUtils.isEmpty(smsLoginPhone)) {
                    ToastUtil.show(getContext(), getContext().getResources().getString(R.string.toast_phone), Toast.LENGTH_LONG);
                    return;
                }
                if (!ToolUtil.isPhoneLegal(smsLoginPhone)) {
                    ToastUtil.show(getContext(), getContext().getResources().getString(R.string.toast_right_phone), Toast.LENGTH_LONG);
                    return;
                }
                String smsLoginCode = iev_sms_text.getText().toString();
                if (TextUtils.isEmpty(smsLoginCode)) {
                    ToastUtil.show(getContext(), getContext().getResources().getString(R.string.toast_code), Toast.LENGTH_LONG);
                    return;
                }
                if (!ToolUtil.isNumeric(smsLoginCode)) {
                    ToastUtil.show(getContext(), getContext().getResources().getString(R.string.toast_code_length), Toast.LENGTH_LONG);
                    return;
                }
                if (!cb_sms.isChecked()) {
                    ToastUtil.show(getContext(), "请勾选注册协议", Toast.LENGTH_LONG);
                    return;
                }
                DialogFragmentHelper.showLoadingDialog(mFragmentManager);
                UserManager.requestIjkRegister(getContext(), smsLoginPhone, "", "", smsLoginCode, new ResponseListener<JSONObject>() {
                    @Override
                    public void onResponse(String requestTag, final JSONObject response) {
                        mhandler.removeMessages(LOGIN_SUCCESS);
                        Message message = mhandler.obtainMessage(LOGIN_SUCCESS, response);
                        mhandler.sendMessage(message);
                    }

                    @Override
                    public void onError(String requestTag, Throwable t) {
                        mhandler.removeMessages(LOGIN_FAILURE);
                        mhandler.sendEmptyMessage(LOGIN_FAILURE);
                    }

                    @Override
                    public void onFinish() {

                    }
                });
                break;
        }
    }
}
